package com.example.service;

import com.example.consts.RbmConst;
import com.example.dao.CompetitionDao;
import com.example.model.pojo.Competition;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description //TODO
 * @Date 2022/9/20 18:50
 * @Author cxy
 **/

@Service
public class CompetitionServiceImpl implements CompetitionService{
    @Autowired
    private CompetitionDao competitionDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public List<Competition> findAll() {
        return competitionDao.findAll();
    }

    @Override
    public void updateStatus() {
        competitionDao.updateStatus();
    }

    @Override
    public List<Integer> findActiveIds() {
        return competitionDao.findActiveIds();
    }

    @Override
    public void updateEndStatus() {
     competitionDao.updateEndStatus();
    }

    @Override
    public List<Integer> findEndIds() {
        return competitionDao.findEndIds();
    }

    @Override
    public String getStatus(Integer cId) {
        String status = (String) redisTemplate.opsForValue().get("c_status_"+cId);
        if(status==null){
            return "0";
        }
        return status;
    }

    @Override
    public void saveToRbm(Integer cId, String username) {
        Map<String,Object> maps =new HashMap<>();
        maps.put("cId",cId);
        maps.put("username",username);

        rabbitTemplate.convertAndSend(RbmConst.SIMPLE_SEC_QUEUE,maps);
    }

    @Override
    public Long downCount(Integer id) {
        Date end=competitionDao.startDate(id);
        Date start=new Date();
        long startTime=start.getTime();
        long endTime=end.getTime();
        long downcount = endTime-startTime;
        System.out.println(downcount);
        if(downcount<0L){
           downcount=0L;
        }
        return downcount;
    }
}
